package com.collect.senegal.zhiNetApi;

import android.content.Context;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.bind.DateTypeAdapter;
import com.collect.senegal.BuildConfig;
import com.collect.senegal.zhiGlobal.zhiAppSettings.ZHIProjectConfigs;
import com.collect.senegal.zhiUtils.MyLogger;

import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.Date;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ZHIHttpApiProvider {
    private static ZHIApiService baseApi;
    public static Gson gson = new GsonBuilder()
            .serializeNulls()
            .registerTypeAdapter(Date.class, new DateTypeAdapter())
            // 过滤字段
            .excludeFieldsWithModifiers(Modifier.PROTECTED)
            .create();

    /**
     * 获取配置文件的api，由于只调用一次，所以不进行静态化了
     */
    public static ZHIApiService settingApi() {

//        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .connectTimeout(60, TimeUnit.SECONDS)
//                .writeTimeout(60, TimeUnit.SECONDS)
//                .readTimeout(60, TimeUnit.SECONDS)
//                .build();

        OkHttpClient okHttpClient = new OkHttpClient();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ZHIProjectConfigs.DEFAULT_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        return retrofit.create(ZHIApiService.class);
    }

    /**
     * 其他接口的api对象
     */
    public static ZHIApiService getApi() {
        if (null == baseApi) {
            //retrofit
            String baseUrl = ZHIProjectConfigs.DEFAULT_URL;
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(genericClient())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            baseApi = retrofit.create(ZHIApiService.class);
        }
        return baseApi;
    }

    public static void resetApi() {
        baseApi = null;
    }


    public static OkHttpClient genericClient() {
        //okhttp
        if (BuildConfig.DEBUG) {
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        }

//                        .connectTimeout(60, TimeUnit.SECONDS)
//                .writeTimeout(60, TimeUnit.SECONDS)
//                .readTimeout(60, TimeUnit.SECONDS)
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .addInterceptor(new OkHttpInterceptor())
                .addInterceptor(httpLoggingInterceptor)
                .build();

        return okHttpClient;
    }

    /**
     * 日志拦截器，打印请求日志
     */
    public static HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(@NonNull String message) {
            MyLogger.showLargeLog(message, "RetrofitLog");
        }
    });

    /**
     * 拦截器实现
     */
    private static class OkHttpInterceptor implements Interceptor {
        private Context context;

        public OkHttpInterceptor() {
        }

        public OkHttpInterceptor(Context context) {
            this.context = context;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();

            MyLogger.i("net", "url:" + original.url());
            MyLogger.i("net", "body:" + original.body());

            Request.Builder builder = original.newBuilder();

            Request request = builder.build();
            Response response = chain.proceed(request);
            //MyLogger.i("net", "response:" + response.body().string());

            return response;
        }
    }
}
